
#include <ESP8266WiFi.h>
#include <EEPROM.h>

// Replace with your network credentials
const char* ssid     = "your wifi ssid";
const char* password = "your  wifi password";

// Set web server port number to 80
WiFiServer server(80);

// Decode HTTP GET value
//String redString = "0";
String colorString = "0";
int colorValue = 0;
//String greenString = "0";
String brightString = "0";
int brightValue = 0;
int warmValue = 0;
int	coldValue = 0;
String funcString = "0";
int funcValue = 0;
int pos1 = 0;
int pos2 = 0;
int pos3 = 0;
int pos4 = 0;

String header;

const int warmPin = 13;     // D1mini -> D7
const int coldPin = 12;   // D1mini -> D6 

// Setting PWM bit resolution
const int resolution = 101;

// Current time
unsigned long currentTime = millis();
// Previous time
unsigned long previousTime = 0; 
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;
String readFromEP = "";


void setup() {
  Serial.begin(115200);
  EEPROM.begin(128);

  analogWriteRange(resolution);
  analogWriteFreq(20000);
  readValue();
	analogOut();  

  
  // Connect to Wi-Fi network with SSID and password
//  Serial.print("Connecting to ");
//  Serial.println(ssid);
   WiFi.begin(ssid, password);
//  while (WiFi.status() != WL_CONNECTED) {
  while (WiFi.localIP().toString() == "0.0.0.0") {
    delay(500);
//    Serial.print(".");
  }
  // Print local IP address and start web server
//  Serial.println("");
//  Serial.println("WiFi connected.");
//  Serial.println("IP address: ");
//  Serial.println(WiFi.localIP());
  server.begin();

}

void loop(){
  WiFiClient client = server.available();   // Listen for incoming clients

  if (client) 
  {                             // If a new client connects,
    currentTime = millis();
    previousTime = currentTime;
//    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected() && currentTime - previousTime <= timeoutTime) 
    {            // loop while the client's connected
      currentTime = millis();
      if (client.available()) 
      {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();
                   
            // Display the HTML web page
            client.println("<!DOCTYPE html><html>");
            client.println("<head><meta charset=\"UTF-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.print("</head><body><a id=\"lightupdate\" href=\"#\" ></a><input id=\"colorRange\" type=\"range\" min=\"0\" max=\"100\" value=\"");
            client.print(colorString);
            client.print("\"step=\"1\" onchange=\"change()\" orient=\"vertical\" style=\"-webkit-appearance: slider-vertical; height: 300px;\">色温<span id=\"colorValue\">");
            client.print(colorString);
            client.print("</span><input id=\"bright\" type=\"range\" min=\"0\" max=\"100\" value=\"");
            client.print(brightString);
            client.print("\"step=\"1\" onchange=\"change()\" orient=\"vertical\" style=\"-webkit-appearance: slider-vertical; height: 300px;\">亮度<span id=\"brightValue\">");
            client.print(brightString);
            client.println("</span><br><button type=\"button\" onclick=\"onoff()\">On/Off</button><button type=\"button\" onclick=\"savedata()\">保存</button>");			
            client.println("<script type='text/javascript'>function change() {var colorValue = document.getElementById('colorRange').value ;");			
            client.println("document.getElementById('colorValue').innerHTML = colorValue;var brightValue = document.getElementById('bright').value;document.getElementById('brightValue').innerHTML = brightValue;");
            client.println("var url = document.getElementById('lightupdate').href = \"?c\" + colorValue + \"b\" + brightValue + \"&\";");
            client.println("var request = new XMLHttpRequest();request.open(\"GET\", url);request.send();}");
            client.print("function savedata() {var url = document.getElementById('lightupdate').href = \"?f3&\";");
            client.println("var request = new XMLHttpRequest();request.open(\"GET\", url);request.send();}");
            client.print("function onoff() {var url = document.getElementById('lightupdate').href = \"?f1&\";");
            client.println("var request = new XMLHttpRequest();request.open(\"GET\", url);request.send();}");
            client.println("</script></body></html>");
			// The HTTP response ends with another blank line
            client.println();

            // Request sample: /?c50b69&
			      // Request sample: /?f1&
            // colorTemp = 50 | Brightness = 69 | f1 = toggle ,f3 = setCurrentValue
            if(header.indexOf("GET /?c") >= 0) {
              pos1 = header.indexOf('c');
              pos2 = header.indexOf('b');
              pos3 = header.indexOf('&');
              colorString = header.substring(pos1+1, pos2);
              brightString = header.substring(pos2+1, pos3);
              
              /*Serial.println(redString.toInt());
              Serial.println(greenString.toInt());
              Serial.println(blueString.toInt());*/
              colorValue = colorString.toInt();
              brightValue = brightString.toInt();
              analogOut();
 
            }
            if(header.indexOf("GET /?f") >= 0) {
              pos1 = header.indexOf('f');
              pos2 = header.indexOf('&');
              funcString = header.substring(pos1+1, pos2);
              funcValue = funcString.toInt();
              switch  (funcValue) 
                { 
                case 1: 
                  toggleLight();
                  break;
                case 2: 
                  readValue();
                  break;
                case 3: 
                  saveData();
                  break;
                default:
                  break;
                }
            
            }
            // Break out of the while loop
            break;
          } else { // if you got a newline, then clear currentLine
            currentLine = "";
            }   
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
          }
      }
    }
    // Clear the header variable
    header = "";
    // Close the connection
    client.stop();
//    Serial.println("Client disconnected.");
//    Serial.println("");
  }
}

void toggleLight()
{
	if (brightValue > 0) 
	{
		brightValue = 0;
		analogOut();
	} else
	{	
		readValue();
		analogOut();
	}
}

void saveData()
{	
	
	String saveString ="c" + colorString + "b" + brightString + "&;";
	for(int n=0; n< saveString.length();n++)
	{
		EEPROM.write(n,saveString[n]);
	}
	EEPROM.commit();
//	Serial.println("SaveDataSuccess");
//	Serial.println(saveString);
}
String readData(int l, int p)
{	
	String temp;
	for (int n = p; n < l+p; ++n)
    {
		if(char(EEPROM.read(n))!=';')
		{
			if(isWhitespace(char(EEPROM.read(n))))
			{
			  //do nothing
			}else 
				temp += String(char(EEPROM.read(n)));	  
		}else 
			n=l+p;     
    }
  return temp;
}
void analogOut()
{

	if (brightValue == 0) 
	{ 
    warmValue = 0;
	  coldValue = 0;
	}
	else if (colorValue >= 50) {
		warmValue=brightValue;
		coldValue=int((1 - ((colorValue - 50)/50.0))*brightValue);
	  }else{
      warmValue=int((1 - ((50 - colorValue)/50.0))*brightValue);
      coldValue=brightValue;
	  }	  
	  analogWrite(warmPin, warmValue);
	  analogWrite(coldPin, coldValue);
}
void readValue()
{	
  readFromEP = readData(128,0);
  pos1 = readFromEP.indexOf('c');
  pos2 = readFromEP.indexOf('b');
  pos3 = readFromEP.indexOf('&');
  colorString = readFromEP.substring(pos1+1, pos2);
  brightString = readFromEP.substring(pos2+1, pos3);
  colorValue = colorString.toInt();
  brightValue = brightString.toInt();
}
